﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using King.Models;
using king.Repository;
using king.models;
using king.Db;
using king.wenjian;

namespace King.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {

            var ef = new EfRepository<Category>();
            var s = ef.Table.FirstOrDefault();
            if (s == null)
            {
                ef.Insert(new Category
                {
                    CategoryName = "天"
                });
            }

            var c = new EfRepository<Product>();
            var d = c.Table.Where(x => x.IsDeleted == false).ToList();
            return View(d);
        }
                public IActionResult Add(int id)
        {
            var ef = new EfRepository<Product>();
            var s = ef.Table.Where(x => x.Id == id).FirstOrDefault();
            return View(s);
        }
        public IActionResult Save(wenjiancs aa)
        {
            var ef = new EfRepository<Product>();

            if (aa.Id > 0)
            {
                var s = ef.Table.Where(x => x.Id == x.Id).FirstOrDefault();
                    s.ProductName=aa.productName;
                    s.Supplier=aa.supplier;

                    s.Price=aa.price;
     
                    s.Stock=aa.stock;

                    s.Remarks=aa.Remarks;

                ef.Update(s);


            }
            else
            {
                ef.Insert(new Product
                {    

                    ProductName=aa.productName,

                    Supplier=aa.supplier,

                    Price=aa.price,
     
                    Stock=aa.stock,

                    Remarks=aa.Remarks

                });
            }
            return Ok();
        }

        public IActionResult Delete(int id)
        {
            var ef = new EfRepository<Product>();
            ef.Delete(id);
            return RedirectToAction("index");


        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
